<template>
    <!-- 使用 Element Plus 的表格组件展示数据 -->
    <el-table :data="tableData" style="width: 100%">
        <!-- 姓名列 -->
        <el-table-column prop="leaveName" label="姓名" width="100" />
       <!-- 修改部门列模板 -->
        <el-table-column prop="departId" label="部门" width="100">
            <template #default="scope">
                <el-td>{{ departmentMap[scope.row.departId] }}</el-td>
            </template>
        </el-table-column>
        <!-- 请假类别列，根据 leaveType 显示不同的请假类别 -->
        <el-table-column prop="leaveType" label="请假类别" width="100">
            <template #default="scope">
                <el-td v-if="scope.row.leaveType == 1">事假</el-td>
                <el-td v-if="scope.row.leaveType == 2">病假</el-td>
                <el-td v-if="scope.row.leaveType == 3">婚假</el-td>
                <el-td v-if="scope.row.leaveType == 4">丧假</el-td>
                <el-td v-if="scope.row.leaveType == 5">产假</el-td>
                <el-td v-if="scope.row.leaveType == 6">补休</el-td>
                <el-td v-if="scope.row.leaveType == 7">工伤</el-td>
                <el-td v-if="scope.row.leaveType == 8">其他</el-td>
            </template>
        </el-table-column>
        <!-- 请假时间列 -->
        <el-table-column prop="leaveCreateTime" label="请假时间" width="200">
            <template #default="scope">
                <el-td>{{ scope.row.leaveCreateTime }}</el-td>
            </template>
        </el-table-column>
        <!-- 总工时列 -->
        <el-table-column prop="totalHours" label="总工时" width="100" />
        <!-- 报到时间列 -->
        <el-table-column prop="coverageTime" label="报到时间" width="200" />
        <!-- 请假事由列 -->
        <el-table-column prop="cause" label="请假事由" width="100" />
        <!-- 部门领导列，根据 departId 显示不同的部门领导 -->
        <el-table-column prop="departmentHeads" label="部门领导" width="100">
            <template #default="scope">
                <el-td v-if="scope.row.departId == 0"></el-td>
                <el-td v-if="scope.row.departId == 3">WW</el-td>
                <el-td v-if="scope.row.departId == 2">LS</el-td>
                <el-td v-if="scope.row.departId == 1">ZS</el-td>
            </template>
        </el-table-column>
        <!-- 审批状态列 -->
        <el-table-column prop="starterName" label="审批状态" width="100" />
        <!-- 审批原因 -->
        <el-table-column prop="yiJian" label="请假事由" width="100" />
        <!-- 操作列，包含修改和删除按钮 -->
        <el-table-column fixed="right" label="操作" min-width="100">
            <template #default="scope">
                <el-button link type="primary" size="small" v-show="scope.row.userId === store.counterStore.userId"
                    @click="dialogFormVisible = true; FanTian(scope.row)">
                    修改
                </el-button>
                <el-button link type="primary" size="small" v-show="scope.row.userId === store.counterStore.userId"
                    @click="Del(scope.row.leaveId)">删除</el-button>
                <el-button link type="primary" size="small" @click="dialogTableVisible = true; FanTian(scope.row)"
                    v-show="scope.row.starterName !== '已完成' && scope.row.userId !== store.counterStore.userId">审批</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 修改对话框 -->
    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
        <el-form :model="form">
            <!-- 姓名 -->
            <el-form-item label="姓名:" prop="leaveName">
                <el-input v-model="form.leaveName" disabled />
            </el-form-item>
            <!-- 部门 -->
            <el-form-item label="部门:" prop="departId">
                <el-select v-model="form.departId" placeholder="请选择部门" disabled>
                    <el-option label="IT信息部" :value="1" />
                    <el-option label="人力资源部" :value="2" />
                    <el-option label="财务部" :value="3" />
                    <el-option label="销售部" :value="4" />
                    <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>
            <!-- 请假类别 -->
            <el-form-item label="请假类别:">
                <el-radio-group v-model="form.leaveType">
                    <el-radio :value="1">事假</el-radio>
                    <el-radio :value="2">病假</el-radio>
                    <el-radio :value="3">婚假</el-radio>
                    <el-radio :value="4">丧假</el-radio>
                    <el-radio :value="5">产假</el-radio>
                    <el-radio :value="6">补休</el-radio>
                    <el-radio :value="7">工伤</el-radio>
                    <el-radio :value="8">其他</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 请假时间 -->
            <el-form-item label="请假时间:" required>
                <div class="demo-date-picker">
                    <div class="block">
                        <el-date-picker type="datetimerange" range-separator="到" start-placeholder="开始时间"
                            end-placeholder="结束时间" :size="size" v-model="datatime" @change="handleDateChange"
                            :picker-options="pickerOptions" disabled />
                    </div>
                </div>
            </el-form-item>
            <!-- 总工时 -->
            <el-form-item label="总工时:" prop="totalHours">
                <el-input v-model="form.totalHours" />
            </el-form-item>
            <!-- 请假事由 -->
            <el-form-item label="请假事由:" prop="cause">
                <el-input v-model="form.cause" type="textarea" />
            </el-form-item>
            <!-- 部门领导 -->
            <el-form-item label="部门领导:">
                <el-text class="mx-1">WW</el-text>
            </el-form-item>
        </el-form>
        <template #footer="scope">
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false; Update()">修改</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 审批弹窗 -->
    <el-dialog v-model="dialogTableVisible" title="审批" width="500">
        <el-form :model="form">
            <!-- 姓名 -->
            <el-form-item label="姓名:" prop="leaveName">
                <el-input v-model="form.leaveName" disabled />
            </el-form-item>
            <!-- 部门 -->
            <el-form-item label="部门:" prop="departId">
                <el-select v-model="form.departId" placeholder="请选择部门" disabled>
                    <el-option label="IT信息部" :value="1" />
                    <el-option label="人力资源部" :value="2" />
                    <el-option label="财务部" :value="3" />
                    <el-option label="销售部" :value="4" />
                    <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>
            <!-- 请假类别 -->
            <el-form-item label="请假类别:">
                <el-radio-group v-model="form.leaveType" disabled>
                    <el-radio :value="1">事假</el-radio>
                    <el-radio :value="2">病假</el-radio>
                    <el-radio :value="3">婚假</el-radio>
                    <el-radio :value="4">丧假</el-radio>
                    <el-radio :value="5">产假</el-radio>
                    <el-radio :value="6">补休</el-radio>
                    <el-radio :value="7">工伤</el-radio>
                    <el-radio :value="8">其他</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 请假时间 -->
            <el-form-item label="请假时间:" required>
                <div class="demo-date-picker">
                    <div class="block">
                        <el-date-picker type="datetimerange" range-separator="到" start-placeholder="开始时间"
                            end-placeholder="结束时间" :size="size" v-model="datatime" @change="handleDateChange"
                            :picker-options="pickerOptions" disabled />
                    </div>
                </div>
            </el-form-item>
            <!-- 总工时 -->
            <el-form-item label="总工时:" prop="totalHours">
                <el-input v-model="form.totalHours" disabled />
            </el-form-item>
            <!-- 请假事由 -->
            <el-form-item label="请假事由:" prop="cause">
                <el-input v-model="form.cause" type="textarea" disabled />
            </el-form-item>
            <!-- 部门领导 -->
            <el-form-item label="审核:">
                <el-radio-group v-model="form.pass">
                    <el-radio :value="1">通过</el-radio>
                    <el-radio :value="2">不通过</el-radio>
                    <el-input v-model="form.yiJian" v-if="form.pass == 2" placeholder="请输入意见" />
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer="scope">
            <div class="dialog-footer">
                <el-button
                    @click="dialogTableVisible = false; Approval(form.instaresid, form.leaveId, form.appstatus, form.yiJian)">提交</el-button>
                <el-button type="primary" @click="dialogTableVisible = false">
                    取消
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize" :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import {read,write} from '@/axios/axiosHelper'

// 获取全局状态管理中的用户信息
const store = useCounterStore();

// 表格数据
const tableData = ref([{
    recodeid: 0,
    instaresid: 0,
    nodeNo: 100,
    nodeName: "",
    userId: 0,
    userName: "",
    yiJian: "",
    createTime: "",
    leaveId: 0,
    leaveName: "",
    departId: 0,
    leaveType: 0,
    leaveCreateTime: "",
    coverageTime: "",
    totalHours: 88,
    cause: "",
    departmentHeads: 0,
    appstatus: 100,
    pass: 0
}])

// 对话框显示状态
const dialogFormVisible = ref(false)
const dialogTableVisible = ref(false)

// 表单数据
const form = reactive({
    recodeid: 0,
    instaresid: 0,
    nodeNo: 100,
    nodeName: "",
    userId: 0,
    userName: "",
    yiJian: "",
    createTime: "",
    leaveId: 0,
    leaveName: "",
    departId: 0,
    leaveType: 0,
    leaveCreateTime: "",
    coverageTime: "",
    totalHours: 88,
    cause: "",
    departmentHeads: 0,
    appstatus: 100,
    pass: 0
})

// 分页信息
const page = ref({
    pageIndex: 1,
    pageSize: 15,
    totalCount: 0,
    totalSize: 0,
})

// 定义映射关系
const departmentMap = {
    1: 'IT信息部',
    2: '人力资源部',
    3: '财务部',
    4: '销售部',
    5: '行政部'
};

// 组件挂载后获取数据
onMounted(() => {
    GetRecode();
})

//审批方法
const Approval = (instaresid: number, leaveId: number, appstatus: number, yiJian: string) => {
    console.log("审批结果", instaresid, leaveId, appstatus, yiJian);
    write.post('/write/api/Leave/Approval', {
        InstafreId: instaresid, // 修改参数名
        leaveId: leaveId,
        appstatus: appstatus,
        yiJian: yiJian,
    }).then((res) => {
        console.log("审批结果", res.data);
        if (res.data.code == 400) {
            ElMessage({
                message: '审批成功',
                type: 'success',
            })
            GetRecode();
        } else {
            ElMessage({
                message: '审批失败',
                type: 'error',
            })
        }
    })
}

// 定义时间选择器的选项
const pickerOptions = {
    selectableRange: '09:00:00 - 17:00:00'
}

// 获取请假记录数据
const GetRecode = () => {
    read.get('/read/api/Leave/Handle', {
        params: {
            pageIndex: page.value.pageIndex,
            pageSize: page.value.pageSize,
            OperatorId: store.counterStore.userId,
        }
    }).then((res) => {
        console.log("请假信息", res.data);
        tableData.value = res.data.data;
    })
}

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    page.value.pageSize = val;
    GetRecode();
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    page.value.pageIndex = val;
    GetRecode();
}

// 日期选择器数据
const datatime = ref<any>([]); // 定义一个空数组来接收数据

// 日期选择器大小
const size = ref<'default' | 'large' | 'small'>('default')
// 处理日期选择器变化
const handleDateChange = (value: any[]) => {
    if (value.length === 2) {
        const startDate = new Date(value[0]);
        const endDate = new Date(value[1]);

        // 计算时间差（以毫秒为单位）
        const timeDiff = endDate.getTime() - startDate.getTime();

        // 将时间差转换为小时数
        const hoursDiff = timeDiff / (1000 * 60 * 60);

        // 将结果赋值给 form.totalHours
        form.totalHours = hoursDiff; // 保留两位小数

        // 同时将日期赋值给 form 的对应字段
        form.leaveCreateTime = value[0];
        form.coverageTime = value[1];
    }
}

//修改记录
const Update = () => {
    write.put('/write/api/Leave/UpdateRecode', {
        leaveId: form.leaveId,
        operatorId: store.counterStore.userId,
        leaveName: form.leaveName,
        departId: form.departId,
        leaveType: form.leaveType,
        leaveCreateTime: form.leaveCreateTime,
        coverageTime: form.coverageTime,
        totalHours: form.totalHours,
        cause: form.cause,
        departmentHeads: form.departmentHeads,
        appstatus: form.appstatus,
    }).then((res) => {
        console.log(res.data);
        if (res.data.code == 400) {
            ElMessage.success('修改成功');
            GetRecode();
        }
    })
}

// 填充表单数据
const FanTian = (row: any) => {
    console.log("填充表单数据", row);
    form.leaveId = row.leaveId;
    form.instaresid = row.instaresid;
    form.leaveName = row.leaveName;
    form.departId = row.departId;
    form.leaveType = row.leaveType;
    form.leaveCreateTime = row.leaveCreateTime;
    form.coverageTime = row.coverageTime;
    form.totalHours = row.totalHours;
    form.cause = row.cause;
    form.departmentHeads = row.departmentHeads;
    form.appstatus = row.appstatus;

    // 将 leaveCreateTime 和 coverageTime 转换为 Date 对象，并赋值给 datatime
    if (row.leaveCreateTime && row.coverageTime) {
        datatime.value = [new Date(row.leaveCreateTime), new Date(row.coverageTime)];
    }
}

// 删除记录
const Del = (leaveId: number) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            ElMessage({
                type: 'success',
                message: '确认删除',
            })
            write.delete('/write/api/Leave/DelRecode', {
                params: {
                    leaveId: leaveId
                }
            }).then((res) => {
                console.log(res.data);
                if (res.data.code == 500) {
                    ElMessage.success('删除成功');
                    GetRecode();
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}
</script>